package net.zigin.nhi.waste.adapter;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.bean.ReceiverBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.depotout.EditReceiverActivity;
import net.zigin.nhi.waste.view.depotout.OutPrintActivity;
import net.zigin.nhi.waste.view.depotout.ReceiverActivity;
import net.zigin.nhi.waste.view.widget.DialogManager;

import java.util.ArrayList;
import java.util.List;

import io.paperdb.Paper;
import io.reactivex.Observable;

public class ReceiverAdapter extends RecyclerView.Adapter<ReceiverAdapter.ViewHolder> {

    public List<ReceiverBean> list;
    private ReceiverActivity mContext;

    public ReceiverAdapter(ReceiverActivity context, List<ReceiverBean> list) {
        this.mContext = context;
        this.list = list;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void notifyData(List<ReceiverBean> beanList) {
        if (beanList != null) {
            list = new ArrayList<>();
            list.addAll(beanList);
        }
        notifyDataSetChanged();
    }

    public interface OnItemClickListener {
        void onClick(int position, ReceiverBean bean);
    }

    private OnItemClickListener listener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_receiver, parent, false);
        return new ViewHolder(view);
    }

    @Override
    @SuppressLint("RecyclerView")
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ReceiverBean bean = list.get(position);
        holder.mCarNumber.setText(bean.getCarCode());
        holder.mName.setText(bean.getRealName());
        holder.mPhone.setText(bean.getMobile());
        holder.mImgDefault.setImageResource("1".equals(bean.getIsDefault()) ? R.drawable.depot_in_selected : R.drawable.depot_in_unselected);

        holder.mEdit.setOnClickListener(v -> {
            Intent intent = new Intent(v.getContext(), EditReceiverActivity.class);
            intent.putExtra("receiver_id", bean.getId());
            v.getContext().startActivity(intent);
        });

        String isManage = Paper.book().read("manage");
        if (StringUtil.isNotEmpty(isManage) && isManage.equals("manage")) {
            holder.mEditLayout.setVisibility(View.VISIBLE);
        } else {
            holder.mEditLayout.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(v -> {
            listener.onClick(position, bean);
        });

        holder.mImgDefault.setOnClickListener(v -> {
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .setDefault(Paper.book().read(Constants.TOKEN), bean.getId());
            DialogManager.getInstance().showLoading(v.getContext());
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    Toast.makeText(v.getContext(), "设置成功！", Toast.LENGTH_SHORT).show();
                    getReceiverList();
                }
            });
        });

        holder.mDelete.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("提示：");
            builder.setMessage("是否删除该接收人？");
            builder.setCancelable(true);            //点击对话框以外的区域是否让对话框消失

            //设置正面按钮
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    deleteReceiver(v, bean.getId());
                    dialog.dismiss();
                }
            });
            //设置反面按钮
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        });
    }

    /**
     * 删除接收人
     */
    private void deleteReceiver(View v, String id) {
        if (StringUtil.isNotEmpty(id)) {
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .removeReceiver(Paper.book().read(Constants.TOKEN), id);
            DialogManager.getInstance().showLoading(v.getContext());
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    Toast.makeText(v.getContext(), "删除成功！", Toast.LENGTH_SHORT).show();
                    mContext.getReceiverList();
                }
            });
        }
    }

    /**
     * 获取接收人列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private void getReceiverList() {
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getReceiverList(Paper.book().read(Constants.TOKEN));
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {

                if (StringUtil.isNotEmpty(data)) {
                    List<ReceiverBean> receiverList = JSONArray.parseArray(data, ReceiverBean.class);
                    notifyData(receiverList);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView mCarNumber;
        private TextView mName;
        private TextView mPhone;
        private ImageView mEdit;
        private LinearLayout mEditLayout;
        private ImageView mImgDefault;
        private TextView mDelete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mCarNumber = itemView.findViewById(R.id.car_number);
            mName = itemView.findViewById(R.id.name);
            mPhone = itemView.findViewById(R.id.phone);
            mEdit = itemView.findViewById(R.id.edit);
            mEditLayout = itemView.findViewById(R.id.edit_layout);
            mImgDefault = itemView.findViewById(R.id.img_default);
            mDelete = itemView.findViewById(R.id.delete);
        }
    }
}
